const express = require("express");
const router = express.Router();
const secretKey = "3uX#7%r&2@!P5cK8";
const expressJWT = require("express-jwt");
const jwt = require("jsonwebtoken");
const User = require("../models/User");
const Card = require("../models/Card")
const moment = require('moment')

router.get('/find/user/:uid', async (req, res) => {
    try {
        const uid = req.params.uid;
        const fieldsToQuery = req.query.fields;
        // 判断如果不是数组或者数组为空，就返回 400 的错误
        if (!Array.isArray(fieldsToQuery) || fieldsToQuery.length === 0) {
            return res.status(400).json({ message: '查询字段不正确' });
        }
        let result = {
            data: {}
        };
        for (const field of fieldsToQuery) {
            const userData = await findUser(uid, field); // 查询用户信息
            if (userData !== null) {
                if (['registrationDate', 'birthday', 'lastLogin'].includes(field)) {
                    const formattedDate = new Date(userData).toString().split('T')[0];
                    result.data[field] = formattedDate;
                } else {
                    result.data[field] = userData; // 将查询结果存入 result.data
                }
            }
        }
        // result.data.followingCount = result.data.followingCount.length;
        console.log(result);
        res.status(200).json(result);
    } catch (error) {
        console.error('查询用户信息失败:', error);
        res.status(500).json({ message: '查询用户信息失败' });
    }
})


router.get('/getUserCardList', async (req, res) => {
    try {
        const id = req.query._id;
        console.log(id);
        const user = await User.findById(id);
        if (!user) {
            return res.status(404).json({ message: '找不到用户' });
        }
        const userCardList = await Card.find({ author: id });
        const formattedCardList = userCardList.map((card) => ({
            _id: card._id,
            title: card.title,
            content: card.content,
            images: card.images,
            like: card.like,
            tags: card.tags,
            author: {
                _id: user._id,
                username: user.username,
                avatar: user.avatar
            },
        }));
        res.status(200).json(formattedCardList)
    } catch (error) {
        res.status(500).json({ message: "服务器错误" })
    }
})



const findUser = async (uid, field) => {
    try {
        if (!User.schema.path(field)) {
            console.log(`字段 ${field} 不存在于用户模型`);
            return null;
        }
        // 查找uid
        const findCondition = { uid: uid };
        // 使用 projection 限制返回字段
        const projection = { [field]: 1, _id: 0 };
        const user = await User.findOne(findCondition, projection);
        if (user) {
            return user[field]; // 返回查询到的字段值
        } else {
            console.log(`未找到uid为${uid}的用户.`);
            return null; // 返回空值表示未找到用户
        }
    } catch (error) {
        console.error('查找用户时出错:', error);
    }
}


module.exports = router;